package com.chhuang.utils.image;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStreamReader;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;

import org.jdesktop.swingx.util.OS;

/**
 * 
 * @author HuangChen
 *
 */
public class TesseractOCR {
	private static final String LANG_OPTION = "-l"; // 英文字母小写l，并非数字1
	private static final String EOL = System.getProperty("line.separator");
	public static final String CHI_SIM = "chi_sim";
	public static final String ENG = "eng";
	
	private static String TESSERACT_PATH = "";
	
	/**
	 * 初始化TESSERACT安装目录
	 * @param tesseractPath
	 */
	public static void init(String tesseractPath){
		TESSERACT_PATH = tesseractPath;
	}
	
	/**
	 * 图片内容转文字，可能需要先调用init()方法初始化TESSERACT安装目录
	 * @param imageFile
	 * @param imageFormat
	 * @param lanage
	 * @return
	 * @throws Exception
	 */
	public static String recognizeText(File imageFile, String imageFormat, String lanage)throws Exception {
		File tempImage = ImageUtil.createImage(imageFile, imageFormat);
		String tempTxtName = UUID.randomUUID().toString();
		File outputFile = new File(imageFile.getParentFile(), tempTxtName+".txt");
		StringBuffer strB = new StringBuffer();
		List<String> cmd = new ArrayList<String>();
		if (OS.isWindowsXP()) {
			cmd.add(TESSERACT_PATH + "/tesseract");
		} else if (OS.isLinux()) {
			cmd.add("tesseract");
		} else {
			cmd.add(TESSERACT_PATH + "/tesseract");
		}
		cmd.add("");
		cmd.add(tempTxtName);
		cmd.add(LANG_OPTION);
		if(CHI_SIM.equalsIgnoreCase(lanage)){
			cmd.add("chi_sim");
		}else{
			cmd.add("eng");
		}

		ProcessBuilder pb = new ProcessBuilder();
		pb.directory(imageFile.getParentFile());

		cmd.set(1, tempImage.getName());
		pb.command(cmd);
		pb.redirectErrorStream(true);

		Process process = pb.start();
		int w = process.waitFor();
		
		// 删除临时正在工作文件
		tempImage.delete();
		
		if (w == 0) {
			BufferedReader in = new BufferedReader(new InputStreamReader(new FileInputStream(outputFile),StandardCharsets.UTF_8));
			String str;
			while ((str = in.readLine()) != null) {
				strB.append(str).append(EOL);
			}
			in.close();
		} else {
			String msg;
			switch (w) {
			case 1:
				msg = "Errors accessing files.There may be spaces in your image's filename.";
				break;
			case 29:
				msg = "Cannot recongnize the image or its selected region.";
				break;
			case 31:
				msg = "Unsupported image format.";
				break;
			default:
				msg = "Errors occurred.";
			}
			throw new RuntimeException(msg);
		}
		
		// 删除临时正在工作文件
		outputFile.delete();

		process.destroy();
		
		return strB.toString();
	}
	
	public static void main(String[] args) {
		TesseractOCR.init("D:/Program Files (x86)/Tesseract-OCR");
		try {
			System.out.println(TesseractOCR.recognizeText(new File("C:/Users/HuangChen/Desktop/a/1.png"), "png", TesseractOCR.CHI_SIM));
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
}